package com.ctshk.rpc.payment.utils.mastercard;

import com.ctshk.rpc.payment.dto.MasterCardPayConfig;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.entity.StringEntity;

/**
 * 服务客户端类，用于通过使用JSON的REST协议发出API请求
 * @author hef
 */
public final class MastercardRestApiClient {

    private static final String UTF8_ENCODING = "UTF-8";

    /**
     * Performs a PUT operation (required for the following API operations: AUTHORIZE, CAPTURE, PAY, REFUND, UPDATE_AUTHORIZATION, VERIFY, VOID, CHECK_3DS_ENROLLMENT,
     * INITIATE_BROWSER_PAYMENT)
     *
     * @param data       JSON payload
     * @param requestUrl API endpoint
     * @param config     contains frequently used information like Merchant ID, API password, etc.
     * @return body
     * @throws Exception
     */
    public static String sendTransaction(String data, String requestUrl, MasterCardPayConfig config) throws Exception {
        HttpPut httpPut = new HttpPut(requestUrl);
        httpPut.setEntity(new StringEntity(data, UTF8_ENCODING));
        return ApiService.executeHTTPMethod(httpPut, config);
    }

    /**
     * Performs a POST operation (required for the following API operations: PROCESS_ACS_RESULT, CREATE_CHECKOUT_SESSION)
     *
     * @param data       JSON payload
     * @param requestUrl API endpoint
     * @param config     contains frequently used information like Merchant ID, API password, etc.
     * @return body
     * @throws Exception
     */
    public  static String postTransaction(String data, String requestUrl, MasterCardPayConfig config) throws Exception {
        HttpPost httpPost = new HttpPost(requestUrl);
        httpPost.setEntity(new StringEntity(data, UTF8_ENCODING));
        return ApiService.executeHTTPMethod(httpPost, config);
    }

    /**
     * Performs a POST operation without a body (required for creating a generic gateway session)
     *
     * @param requestUrl API endpoint
     * @param config     contains frequently used information like Merchant ID, API password, etc.
     * @return body
     * @throws Exception
     */
    public static String postTransaction(String requestUrl, MasterCardPayConfig config) throws Exception {
        HttpPost httpPost = new HttpPost(requestUrl);
        return ApiService.executeHTTPMethod(httpPost, config);
    }

    /**
     * Performs a GET operation (required for the following API operations: Retrieve session, Retrieve transaction, Retrieve order)
     *
     * @param requestUrl API endpoint
     * @param config     contains frequently used information like Merchant ID, API password, etc.
     * @return body
     * @throws Exception
     */
    public static String getTransaction(String requestUrl, MasterCardPayConfig config) throws Exception {
        HttpGet httpGet = new HttpGet(requestUrl);
        return ApiService.executeHTTPMethod(httpGet, config);
    }
}
